// 主控
var main = {
    pkinit: function(list) {
        var self = main,
            section = self.section;
            
        // 检查上期开奖时间
        detection.lastopentime(list.res.create_time, list.bj_time);

        // 设置上一期期号为当前期号
        self.section.prevno = list.res.no;
        
        // 页面显示
        createDatabase(list.res);

        // 下期期号
        document.querySelector('#ipt-nextno').innerHTML = Number(self.section.prevno) + 1;

        // 计算北京时间和本地时间之差
        var now = parseInt(new Date().getTime() / 1000);
        section.calc = list.bj_time - now;

        tool.p('---------------------------------------');
        tool.p('北京时间 ' + list.bj_time);
        tool.p('本地时间 ' + now);
        tool.p('时差 ' + section.calc);
        tool.p('进入倒计时');
        countdown.start();
    },
    // 时区
    section: {
        // 开盘时间
        min: ('09:07:00').replace(/:/gi, ''),
        // 封盘时间
        max: ('23:58:20').replace(/:/gi, ''),
        // 计算北京时间和本地时间之差
        calc: 0,
        // 上一期期号
        prevno: 0
    },
    // 采集回调
    realCollectCB: function(list) {
        var self = main;
        tool.p('---------------------------------------');
        tool.p('判断采集结果期号与当前期号');
        if(list.no == self.section.prevno) {
            tool.p('期号一致，隔一秒继续查询');
            setTimeout(function() {
                realcollect.init();
            }, 3000);
        } else {
            tool.p('期号不一致，刷新页面');
            countdown.stop();
            setTimeout(function() {
                window.location.reload();
            }, 1000);
        }
    }
};

window.onload = function() {
    // 初始化ajax
    ajax.config.state({
        200: true,
        201: true
    });

    initDatabasePK10();
}

// 初始化接口
function initDatabasePK10() {
    tool.p('---------------------------------------');
    tool.p('/api?pk10.init 准备初始化');
    ajax.get('/api?pk10.init', function(res) {
        if(res.state) {
            tool.p('/api?pk10.init 初始化成功');
            // 执行成功回调
            main.pkinit(res.data);
        } else {
            tool.p('/api?pk10.init 初始化失败');
            tool.p('/api?pk10.init 1秒后重新初始化');
            setTimeout(function() {
                initDatabasePK10();
            }, 1000);
        }
    });
}

// 采集器
var realcollect = {
    jude: false,
    init: function() {
        var self = realcollect;
        if(self.jude) return;
        self.jude = true;
        tool.p('---------------------------------------');
        tool.p('/api?pk10.realCollect 采集结果');
        ajax.get('/api?pk10.realCollect', function(res) {
            if(res.state) {
                tool.p('/api?pk10.realCollect 采集成功');
                self.jude = false;
                // 执行回调
                main.realCollectCB(res.data);
            } else {
                tool.p('/api?pk10.realCollect 采集失败');
                tool.p('/api?pk10.realCollect 1秒后重新采集');
                setTimeout(function() {
                    self.jude = false;
                    self.init();
                }, 1000);
            }
        });
    }
}

// 倒计时
var countdown = {
    worker: null,
    start: function() {
        var self = countdown;
        self.worker = new Worker("../../../../public/triplan/js/collect.real.work.js");
        // 传参给子线程
        self.worker.postMessage({
            calc: main.section.calc
        });
        //设置postMessage的监听
        self.worker.onmessage = function(message) {
            var list = message.data;
            //detection.distance(list.now);
            detection.isopen(list.now);
        };
        // 监听报错
        self.worker.onerror = function(error) {
            worker.terminate();
            console.log(error.filename, error.lineno, error.message);
        }
    },
    stop: function() {
        var self = countdown;
        // terminate 方法用于停止worker的继续运行
        self.worker.terminate();
    }
};

// 检测
var detection = {
    // 检测是否开盘
    isopen: function(now) {
        tool.p('---------------------------------------');
        tool.p('判断是否开盘');
        var section = main.section;
        // 获取时分秒
        var hhiiss = tool.formatDate('hhiiss', now);
        if(hhiiss >= section.min && hhiiss <= section.max) {
            tool.p('已开盘');
            document.querySelector('#ipt-nextno').innerHTML = Number(main.section.prevno) + 1;
            detection.distance(now);
        } else {
            tool.p('未开盘 ------ 等待开盘');
            document.querySelector('#ipt-nextno').innerHTML = '<font style="color:orangered;">未开盘</font>';
            detection.refreshpage(now);
        }
    },
    // 检测距离下一次开奖还有多久时间
    distance: function(now) {
        var ii = tool.formatDate('ii', now);
        var i = String(ii)[1];
        var ss = Number(tool.formatDate('ss', now));
        // 判断大于02分还是大于07分
        var dif_i = 0;
        var dif_s = 59;
        if(i < 2) {
            // 下期开奖时间*2分
            dif_i = 2;
        } else if(i >= 2 && i < 7) {
            // 下期开奖时间*7分
            dif_i = 7;
        } else if(i >= 7) {
            // 下期开奖时间*2分
            dif_i = 7 + 5;
        }
        var res_i = Math.abs(Number(dif_i) - 1 - Number(i));
        var res_s = Math.abs(dif_s - ss);
        var res_ii = '0' + res_i;
        var res_ss = res_s > 9 ? res_s : '0' + res_s;
        //tool.p(res_ii + ':' + res_ss);
        document.querySelector('#ipt-countdown').innerHTML = res_ii + ':' + res_ss;
        detection.islottery(res_i, res_s);
    },
    // 是否到时间开奖
    islottery: function(res_i, res_s) {
        // 04:30之后，这个时间段都是开奖中
        if(Number(res_i) == 4 && Number(res_s) == 30) {
            // 时间到，开始采集结果
            tool.p('---------------------------------------');
            tool.p('开始采集数据');
            realcollect.init();
            // 开奖中
            document.querySelector('#ipt-nextno').innerHTML = '开奖中';
        } else {
            // 开奖时间未到
            tool.p('开奖时间未到');
        }
    },
    // 检测上期开奖时间
    lastopentime: function(time, bjtime) {
        var section = main.section;
        var hhiiss = tool.formatDate('hhiiss', time);
        // 判断是否在开盘时间内
        if (hhiiss > section.min && hhiiss < section.max) {
            // 判断距离现在相差多少秒，不能超过5分30秒
            if (Number(bjtime) - Number(time) > (5 * 60 + 30)) {
                realcollect.init();
            }
        }
    },
    // 未开盘，10分钟刷新一次页面
    refreshpage: function(now) {
        var dif_i = 9;
        var dif_s = 59;
        var ii = tool.formatDate('ii', now);
        var i = String(ii)[1];
        var ss = tool.formatDate('ss', now);
        var res_i = dif_i - Number(i);
        var res_s = dif_s - Number(ss);
        var res_ii = '0' + res_i;
        var res_ss = res_s > 9 ? res_s : '0' + res_s;
        document.querySelector('#ipt-countdown').innerHTML = res_ii + ':' + res_ss;
        if (res_i == 0 && res_s == 0) {
            window.location.reload();
        }
    }
};

function createDatabase(data) {
    var list = data;
    var ele = '';
    var domDiv = document.createElement('div');
    domDiv.className = 'livebox';
    ele += '<p class="text-center">';
    ele += '<small class="fs12r">第<font class="p-x-1x">' + list.no + '</font>期开奖号码</small>';
    ele += '</p>';
    ele += '<ul class="awardresults p-y-2x">';
    for (var i = 1; i <= 10; i++) {
        var v = 'v' + i;
        ele += '<li>';
        ele += '<img class="numbar" src="../../../../public/triplan/image/numresults/' + Number(list[v]) + '.svg" />';
        ele += '</li>';
    }
    ele += '</ul>';
    ele += '<div class="winresults dis-table m-b-1x">';
    ele += '<span class="dis-cell line-right">';
    ele += '<img style="height: 28px; float: left;" src="../../../../public/triplan/image/numresults/' + Number(list['v1']) + '.svg" />';
    ele += '<font class="p-x-1x line-right">冠</font>';
    ele += '<font class="p-x-1x">' + winrule.compare.sord(list['v1']) + '</font>';
    ele += '<font class="p-x-1x">' + winrule.compare.bors(list['v1']) + '</font>';
    ele += '</span>';
    ele += '<span class="dis-cell">';
    ele += '<img style="height: 28px; float: left;" src="../../../../public/triplan/image/numresults/' + Number(list['v2']) + '.svg" />';
    ele += '<font class="p-x-1x line-right">亚</font>';
    ele += '<font class="p-x-1x">' + winrule.compare.sord(list['v2']) + '</font>';
    ele += '<font class="p-x-1x">' + winrule.compare.bors(list['v2']) + '</font>';
    ele += '</span>';
    ele += '</div>';
    ele += '<div class="winresults dis-table text-center">';
    ele += '<div class="dis-cell line-right">';
    ele += '<p class="line-bottom">1-5龙虎</p>';
    ele += '<ul class="dis-table linefive">';
    // [1|10]
    ele += '<li class="dis-cell line-right">' + winrule.longhu(list['v1'], list['v10']) + '</li>';
    // [2|9]
    ele += '<li class="dis-cell line-right">' + winrule.longhu(list['v2'], list['v9']) + '</li>';
    // [3|8]
    ele += '<li class="dis-cell line-right">' + winrule.longhu(list['v3'], list['v8']) + '</li>';
    // [4|7]
    ele += '<li class="dis-cell line-right">' + winrule.longhu(list['v4'], list['v7']) + '</li>';
    // [5|6]
    ele += '<li class="dis-cell">' + winrule.longhu(list['v5'], list['v6']) + '</li>';
    ele += '</ul>';
    ele += '</div>';
    ele += '<div class="dis-cell">';
    ele += '<p class="line-bottom">冠亚和</p>';
    ele += '<ul class="dis-table linethree">';
    ele += '<li class="dis-cell line-right">' + winrule.aband.andor(list['v1'], list['v2']) + '</li>';
    ele += '<li class="dis-cell line-right">' + winrule.aband.sord(list['v1'], list['v2']) + '</li>';
    ele += '<li class="dis-cell">' + winrule.aband.bors(list['v1'], list['v2']) + '</li>';
    ele += '</ul>';
    ele += '</div>';
    ele += '</div>';
    domDiv.innerHTML = ele;
    document.querySelector('#databaseVlist').insertBefore(domDiv, document.querySelector('#databaseVlist').getElementsByTagName('div')[0]);
}

// 规则计算
var winrule = {
    // 龙虎计算
    longhu: function() {
        if(Number(arguments[0]) > Number(arguments[1])) {
            return '龙';
        } else {
            return '虎';
        }
    },
    // “冠” “亚” 比较
    compare: {
        // 比大小
        bors: function() {
            if(arguments[0] <= 5) {
                return '小';
            } else {
                return '大';
            }
        },
        // 比单双
        sord: function() {
            if(arguments[0] % 2 == 1) {
                return '单';
            } else {
                return '双';
            }
        }
    },
    // 冠亚和
    aband: {
        // “冠亚和”比大小
        bors: function() {
            var val = Number(arguments[0]) + Number(arguments[1]);
            if(val <= 11) {
                return '小';
            } else {
                return '大';
            }
        },
        // “冠亚和”比单双
        sord: function() {
            var val = Number(arguments[0]) + Number(arguments[1]);
            if(val % 2 == 1) {
                return '单';
            } else {
                return '双';
            }
        },
        // “冠亚和”
        andor: function() {
            var val = Number(arguments[0]) + Number(arguments[1]);
            return val;
        }
    }
};